package com.lengyu.iottransfer.gateway.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lengyu.iottransfer.gateway.common.BaseConstant;
import com.lengyu.iottransfer.gateway.common.HttpResultDto;
import com.lengyu.iottransfer.gateway.entity.User;
import com.lengyu.iottransfer.gateway.security.jwt.JwtUtils;
import com.lengyu.iottransfer.gateway.security.rest.dto.JwtUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class LoginFilter extends UsernamePasswordAuthenticationFilter {
    private AuthenticationManager authenticationManager ;

    public LoginFilter(AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;
        super.setFilterProcessesUrl("/oauth/login");

    }

    // 接受并解析用户的凭证
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request,
                                                HttpServletResponse response) throws AuthenticationException {
            String username = obtainUsername(request);
            username = (username != null) ? username : "";
            username = username.trim();
            String password = obtainPassword(request);
            password = (password != null) ? password : "";
            User user = new User();
            user.setUsername(username);
            user.setPassword(password);
            System.err.println(user.getUsername()+"\t"+user.getPassword());
            return authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(user.getUsername(),user.getPassword(),new ArrayList<>())
                    //这里的ArrayList是权限列表,本项目在里面只存取了用户组信息
            );
    }

    //成功登录后 该方法被调用
    @Override

    protected void successfulAuthentication(HttpServletRequest request,
                                            HttpServletResponse response,
                                            FilterChain chain,
                                            Authentication authResult) throws IOException, ServletException {

        JwtUser jwtUser = (JwtUser) authResult.getPrincipal();

        System.err.println("成功登录: -> \n"+"\t"+jwtUser);
        //生成一个永久令牌
//        Collection<GrantedAuthority> authorities = jwtUser.getAuthorities();
//        String group = "";
//        for (GrantedAuthority authority : authorities){
//            group = authority.getAuthority();
//        }
        jwtUser.setPassword(StringUtils.EMPTY);
        String token = JwtUtils.GenToken(jwtUser,jwtUser.getId(),false);

        System.err.println(token);

        response.setHeader(BaseConstant.Oauth.HEADER_PARAM.getVal(), BaseConstant.Oauth.TOKEN_PREFIX.getVal()+token);

//        ResultUtils.initResponse(response);

        Map<String,String> r = new HashMap<>();

        r.put("token",token);

        response.getWriter().write(new ObjectMapper().writeValueAsString(HttpResultDto.success(r)));

    }

    // 这是验证失败时候调用的方法

    @Override

    protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException, ServletException {
        response.getWriter().write(new ObjectMapper().writeValueAsString(HttpResultDto.failed(BaseConstant.ReturnMessage.USER_OR_PWD_ERR.getVal())));
    }

}
